package com.wuxiaofan.admin.config;

import com.alibaba.fastjson.JSONObject;
import com.wuxiaofan.admin.client.MemberClient;
import com.wuxiaofan.common.vo.ReturnResult;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Arrays;
import java.util.Date;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author wuxiaofan
 * @date 2021/11/22 2:14 下午
 */
@Slf4j
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Resource
    MyUserDetailsService myUserDetailsService;
    @Resource
    private MemberClient memberClient;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        ReturnResult returnResult = memberClient.findByUsername(authentication.getName());
        log.info("{}登录信息:{}",authentication.getName(), ObjectUtils.toString(returnResult.getResult()));
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(returnResult.getResult()));
        if(!jsonObject.getString("password").equals(password)){
            throw new UsernameNotFoundException("用户名密码不匹配 !");
        }
        // 生成jwt访问令牌
        String jwt = Jwts.builder()
                // 用户角色
                .claim("role", "admin")
                // 主题 - 存用户名
                .setSubject(authentication.getName())
                // 过期时间 - 30分钟
                .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000))
                // 加密算法和密钥
                .signWith(SignatureAlgorithm.HS512, "wuxiaofan")
                .compact();
        return new UsernamePasswordAuthenticationToken(userName, password, Arrays.asList( new SimpleGrantedAuthority("admin")));
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
